let handler = null

// 此模块只用来选择3dtiles的组件

// 初始化
export function init(viewer = window.viewer) {
    handler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas)
}

// 销毁
export function destroy() {
    if (!handler) return
    handler.destroy()
    handler = null
}

// 开启选择
export function startSelect({ onSelect = () => { }, viewer = window.viewer }) {
    if (handler.getInputAction(Cesium.ScreenSpaceEventType.LEFT_CLICK)) {
        console.error('选择事件已注册')
        return
    }
    handler.setInputAction((movement) => {
        const scene = viewer.scene
        const feature = scene.pick(movement.position)
        if (!Cesium.defined(feature)) {
            return
        }
        const bool = scene.globe.depthTestAgainstTerrain
        scene.globe.depthTestAgainstTerrain = true;
        let earthPosition = scene.pickPosition(movement.position)
        scene.globe.depthTestAgainstTerrain = bool
        if (feature instanceof Cesium.Cesium3DTileFeature) {
            onSelect(feature, getFeatureData(feature), earthPosition)
        } else {
            onSelect(null)
        }
    }, Cesium.ScreenSpaceEventType.LEFT_CLICK)
}

// 关闭选择
export function stopSelect() {
    handler.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_CLICK)
}

// 设置组件颜色
export function setFeatureColor({ feature, color, viewer = window.viewer }) {
    feature.color = color instanceof Cesium.Color ? color : Cesium.Color.fromCssColorString(color)
    if (viewer.scene.requestRenderMode) {
        viewer.scene.requestRender();
    }
}

// 设置指定组件与其余组件的颜色
export function setOtherFeatureColor({ feature, color, otherColor, viewer = window.viewer }) {
    let cesiumColor = null
    let cesiumOtherColor = null
    if (color) {
        cesiumColor = color instanceof Cesium.Color ? color : Cesium.Color.fromCssColorString(color)
    }
    if (otherColor) {
        cesiumOtherColor = otherColor instanceof Cesium.Color ? otherColor : Cesium.Color.fromCssColorString(otherColor)
    }
    const condition = {
        evaluateColor: function (f, result) {
            if (f == feature) {
                return cesiumColor
            } else {
                return cesiumOtherColor
            }
        },
    }
    if (feature.tileset.style) {
        const tilesetStyle = feature.tileset.style.style
        tilesetStyle.color = condition
        feature.tileset.style = new Cesium.Cesium3DTileStyle(tilesetStyle)
    } else {
        feature.tileset.style = new Cesium.Cesium3DTileStyle({
            color: condition,
        });
    }
    if (viewer.scene.requestRenderMode) {
        viewer.scene.requestRender();
    }
}

// 获取组件全部属性
export function getFeatureData(feature) {
    const keys = feature.getPropertyNames()
    const data = {}
    keys.forEach(key => {
        data[key] = feature.getProperty(key)
    })
    return data
}